package cn.tellfish.studydemo.sync;

import java.util.concurrent.CountDownLatch;

/**
 * 数字添加的线程安全
 */
public class IncreaseDemo2 {

    private int num = 0;

    private void increase(){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        num ++;
    }

    public int getNum() {
        return num;
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(500);
        IncreaseDemo2 increaseDemo = new IncreaseDemo2();
        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                latch.countDown();
                try {
                    latch.await();
                    increaseDemo.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }

        while (Thread.activeCount() > 1){
            Thread.yield();
        }

        System.out.println(increaseDemo.getNum());

    }



}
